#include "TitleState.hpp"
#include "Utility.hpp"
#include "ResourceHolder.hpp"

#include <SFML/Graphics/RenderWindow.hpp>



TitleState::TitleState(StateStack& stack, Context context)
: State(stack, context)
, mText()
, mShowText(true)
, mTextEffectTime(sf::Time::Zero)
, anim(0)
, accu(sf::Time::Zero)
, mCharacter(getContext().textures->get(Textures::Robotarm))
{
	mBackgroundSprite.setTexture(context.textures->get(Textures::TitleScreen));
	mCharacter.setTexture(getContext().textures->get(Textures::Robotarm));
	mCharacter.setPosition(300 + randomInt(600), 300 + randomInt(400));
	mCharacter.setScale(sf::Vector2f(0.6f, 0.6f));
	mText.setFont(context.fonts->get(Fonts::Main));
	mText.setString("Press any key to start");
	centerOrigin(mText);
	mText.setPosition(sf::Vector2f(context.window->getSize() / 2u));
}

void TitleState::draw()
{
	sf::RenderWindow& window = *getContext().window;
	window.draw(mBackgroundSprite);	
	window.draw(mCharacter);
	if (mShowText)
	{		
		window.draw(mText);
	}	
}

bool TitleState::update(sf::Time dt)
{
	mTextEffectTime += dt;
	accu += dt;

	if (mTextEffectTime >= sf::seconds(0.5f))
	{
		mShowText = !mShowText;
		mTextEffectTime = sf::Time::Zero;
	}
	mCharacter.setPosition(400 + 200* sinf(accu.asSeconds()), 400);
	mCharacter.update(dt);
	
	

	return true;
}

bool TitleState::handleEvent(const sf::Event& event)
{
	// If any key is pressed, trigger the next screen
	if (event.type == sf::Event::KeyReleased)
	{
		if (event.key.code == sf::Keyboard::Space)
		{
			
				if (anim < 4)
					mCharacter.setAnimation(++anim);
				else
				{
					anim = 0;
					mCharacter.setAnimation(0);
				}
			

		}		
		else
		{
			requestStackPop();
			requestStackPush(States::Menu);
		}
		
	}

	return true;
}